package com.smartTerminal.perMatters.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.smartTerminal.perMatters.entity.DynamicInfo;
import com.smartTerminal.perMatters.entity.DynamicReturn;
import com.smartTerminal.perMatters.entity.DynamicReturnSource;
import com.smartTerminal.perMatters.entity.FileData;
import com.smartTerminal.perMatters.entity.ItemData;
import com.smartTerminal.perMatters.entity.ItemInfo;
import com.smartTerminal.perMatters.entity.Items;
import com.smartTerminal.perMatters.entity.OrItems;
import com.smartTerminal.perMatters.entity.Page;
import com.smartTerminal.perMatters.entity.Receipt;
import com.smartTerminal.perMatters.entity.UserAdr;
import com.smartTerminal.perMatters.entity.UserItemInfo;
import com.smartTerminal.perMatters.entity.UploadFileInfo;
import com.smartTerminal.perMatters.service.GetOrItemsService;
import com.smartTerminal.user.entity.User;
import com.smartTerminal.user.service.UserService;
import com.smartTerminal.utils.Base64Util;
import com.smartTerminal.utils.StringUtils;
import com.smartTerminal.utils.XmlUtils;

/**
 * 
 * ClassName: GetServiceOrItemsController
 * 
 * @Description: 个人办事
 * @author zhang yachao
 * @Description: TODO
 * @date: 2018年1月9日 下午2:53:13
 */

@Controller
public class GetOrItemsController {
	@Autowired
	private GetOrItemsService getOrItemsService;
	@Autowired
	private UserService userService;

	/**
	 * 
	 * @Description: 获取个人办事事项
	 * @author zhang yachao
	 * @param type
	 *            事项类型(1企业办事；2个人办事；)
	 * @param tagname
	 *            类型名称，用于模糊搜索可以为空
	 * @return Json字符串
	 */
	@RequestMapping("/getoritems")
	public String getServiceOrItems(String type, String tagname,
			HttpServletRequest request) {
		String orItems = getOrItemsService.getServiceOrItems(type, "");
		String code = JSONObject.parseObject(orItems).getString("code");
		if (!"0".equals(code)) {
			request.setAttribute("tips", "获取事项信息失败");
			return "user/error";
		}
		JSONObject obj = JSON.parseObject(orItems);
		String jsonArray = obj.getString("DATA");
		List<OrItems> list = JSON.parseArray(jsonArray, OrItems.class);
		request.setAttribute("oritems", list); // 个人办事事项信息
		// 为维护系统添加的type，后续可以删除
		request.setAttribute("type", type);
		return "permatters/todolist"; // 跳转到事项页面
	}

	@RequestMapping("/getoritemss")
	public String getServiceOrItemss(String type, String tagname,
			HttpServletRequest request) {
		String orItems = getOrItemsService.getServiceOrItems(type, "");
		String code = JSONObject.parseObject(orItems).getString("code");
		if (!"0".equals(code)) {
			request.setAttribute("tips", "获取事项信息失败");
			return "user/error";
		}
		JSONObject obj = JSON.parseObject(orItems);
		String jsonArray = obj.getString("DATA");
		List<OrItems> list = JSON.parseArray(jsonArray, OrItems.class);
		request.setAttribute("oritems", list); // 个人办事事项信息
		// 为维护系统添加的type，后续可以删除
		request.setAttribute("type", type);
		return "permatters/itemSearch"; // 跳转到事项页面
	}

	/**
	 * 
	 * @Description: 根据事项类型获取该类型下的所有事项列表
	 * @author zhang yachao
	 * @param type
	 *            父类型(1企业办事；2个人办事)
	 * @param tag_id
	 *            事项类型id(tag_id)
	 * @param itemName
	 *            事项名称（可以不传，用于模糊搜索）
	 * @param currentpage
	 *            分页信息：当前第几页
	 * @param pagesize
	 *            分页信息：当前页显示几条数据
	 * @param token
	 *            登录成功后会存放在session中
	 * @return
	 */
	@RequestMapping("/getitembytagid")
	public String getItemByTagId(String type, String tag_id, String itemName,
			String currentpage, String pagesize, String tag_name,
			HttpServletRequest request) {
		String str = tag_name;
		String items = getOrItemsService.getItemByTagId(type, tag_id, "",
				currentpage, pagesize, "");
		String rootData = JSONObject.parseObject(items).getString("DATA");
		String code = JSONObject.parseObject(items).getString("code");
		if (!"0".equals(code)) {
			request.setAttribute("tips", "获取事项列表失败");
			return "user/error";
		}
		String dataArray = JSON.parseObject(rootData).getString("DATA");
		if (StringUtils.isEmpty(dataArray)) {
			request.setAttribute("tips", "该类型下暂无网上办理事项");
			return "user/error";
		}
		List<Items> itemsList = JSON.parseArray(dataArray, Items.class);// 所有事项列表数据
		String currentRows = JSONObject.parseObject(rootData).getString("ROWS");// 分页总页数
		OrItems orItems = new OrItems();
		orItems.setTAG_TYPE(type);
		orItems.setTAG_ID(tag_id);
		orItems.setCurrentpage(Integer.parseInt(currentpage));
		orItems.setPagesize(Integer.parseInt(pagesize));
		orItems.setCurrentRows((int) Math.ceil(Double.parseDouble(currentRows)
				/ Double.parseDouble(pagesize)));
		orItems.setTAG_NAME(str);
		request.setAttribute("orItems", orItems);
		request.setAttribute("itemsList", itemsList);
		// 为维护系统添加的types，后续可以删除
		request.getSession().setAttribute("getSxbmList", itemsList);
		request.setAttribute("types", request.getParameter("types"));
		return "permatters/new-list";
	}

	/**
	 * 
	 * @Description: 根据事项名称模糊查找所有事项列表
	 * @author lancelot
	 * @param itemName
	 *            事项名称
	 * @param currentpage
	 *            当前页面
	 * @param pagesize
	 *            每页多少条数据
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/getItemPageforName")
	public String getItemPageforName(String itemName, String currentpage,
			String pagesize, HttpServletRequest request,
			HttpServletResponse response) {
		List<Items> list = new ArrayList<Items>();
		Page page = new Page();
		page.setCurrentpage(Integer.valueOf(currentpage));
		page.setPageSize(Integer.valueOf(pagesize));
		list = getOrItemsService.getItemPageforName(itemName, currentpage,
				pagesize, page);

		request.setAttribute("itemName", itemName);
		if (list != null && list.size() > 0) {
			request.setAttribute("page", page);
			request.setAttribute("itemsList", list);
			request.getSession().setAttribute("getSxbmList", list);
			return "permatters/itemListByName";
		} else {
			request.setAttribute("tips", "对不起，没有找着你需要的办理事项，请返回重新查找~！");
			return "user/error";
		}
	}

	/**
	 * 
	 * @Description: 网上办事-根据事项id获取事办事指南信息接口
	 * @author zhang yachao
	 * @param itemId
	 *            事项id，根据getItemByTagId接口获取HID
	 * @return
	 */
	@RequestMapping("/getitem")
	public String getItem(String itemId, HttpServletRequest request) {
		String data = getOrItemsService.getItem("", itemId);
		String code = JSONObject.parseObject(data).getString("code");
		if (!"0".equals(code)) {
			request.setAttribute("tips", "获取办事指南失败");
			return "user/error";
		}

		String fileData = JSONObject.parseObject(data).getString("FILE_DATA");
		String itemData = JSONObject.parseObject(data).getString("ITEM_DATA");
		List<FileData> fileDataList = JSON.parseArray(fileData, FileData.class);
		JSONObject itemDataJson = JSONObject.parseObject(itemData);
		ItemData itemDataObj = new ItemData(itemDataJson.getString("BLSJ"),
				itemDataJson.getString("BLWINDOW"),
				itemDataJson.getString("DEGREE"),
				itemDataJson.getString("ITEMID"),
				itemDataJson.getString("ITEMNAME"),
				itemDataJson.getString("JDTSDH"),
				itemDataJson.getString("NORMACCEPTDEPART"),
				itemDataJson.getString("NORMTIMELIMIT"),
				itemDataJson.getString("SCID"), itemDataJson.getString("SDYJ"),
				itemDataJson.getString("SFJE"), itemDataJson.getString("SFSF"),
				itemDataJson.getString("SXBM"),
				itemDataJson.getString("TRANSACT_CONDITION"),
				itemDataJson.getString("ZXMKZXDH"));
		Receipt receipt = new Receipt();
		// 为维护系统添加的type和types，后续可以删除
		request.setAttribute("types", request.getParameter("types"));
		request.setAttribute("type", request.getParameter("type"));
		receipt.setITMENAME(itemDataJson.getString("ITEMNAME"));
		receipt.setNORMACCEPTDEPART(itemDataJson.getString("NORMACCEPTDEPART"));
		receipt.setTELPHONE(itemDataJson.getString("ZXMKZXDH"));

		//
		request.getSession().setAttribute("receipt", receipt);
		List<Items> itemList1 = (List<Items>) request.getSession()
				.getAttribute("getSxbmList");
		request.removeAttribute("getSxbmList");
		for (Items its : itemList1) {
			if (its.getHID().equals(itemDataObj.getITEMID())) {
				itemDataObj.setISZXBL(its.getISZXBL());
			}
		}

		request.setAttribute("itemDataObj", itemDataObj);
		request.setAttribute("itemName", request.getParameter("itemName"));
		request.setAttribute("fileDataList", fileDataList);
		return "permatters/item"; // 跳转到网上办事-查询当前办理人、办理事项的基本信息
	}

	/**
	 * 
	 * @Description: 网上办事-查询当前办理人、办理事项的基本信息
	 * @author zhang yachao
	 * @param itemId
	 *            事项id(通过getItem获得)
	 * @param session
	 *            用来获取token
	 * @return
	 */
	@RequestMapping("/getuseroritem")
	public String getUserOrItem(String itemId, HttpServletRequest request) {
		// 为维护系统添加的type，后续可以删除
		String types = request.getParameter("types");
		String type = request.getParameter("type");
		if ("3".equals(type) || "1".equals(types)) {
			request.setAttribute("tips", "系统正在开发中。。。。。。");
			return "user/error";
		}

		User user = (User) request.getSession().getAttribute("USER");
		if (user == null || StringUtils.isEmpty(user.getAuthToken())) {
			user = new User();
			user.setService("redirect:/getuseroritem?itemId=" + itemId);
			request.setAttribute("user", user);
			return "user/login";
		}
		String token = user.getAuthToken();
		String data = getOrItemsService.getUserOrItem(token, itemId);
		String code = JSONObject.parseObject(data).getString("code");
		if (!"0".equals(code)) {
			request.setAttribute("tips", "获取办理人、办理事项的基本信息失败");
			return "user/error";
		}
		String DYNAMICFORM = JSONObject.parseObject(data).getString(
				"DYNAMICFORM");
		String FILEDATA = JSONObject.parseObject(data).getString("FILEDATA");
		String adrData = JSONObject.parseObject(data).getString("ADR_DATA");
		String infoData = JSONObject.parseObject(data).getString("INFO_DATA");
		List<UserAdr> list = JSON.parseArray(adrData, UserAdr.class);
		JSONObject infoObj = JSONObject.parseObject(infoData);
		UserItemInfo uInfo = new UserItemInfo(infoObj.getString("USERDUTY"),
				infoObj.getString("QYTXDZ"), infoObj.getString("MOBILE_NUM"),
				infoObj.getString("ITEMID"), infoObj.getString("COMPANYNAME"),
				infoObj.getString("USERNAME"), infoObj.getString("SXBM"),
				infoObj.getString("ITEMNAME"), infoObj.getString("REALNAME"),
				infoObj.getString("BUSINESSLICENCE"),
				infoObj.getString("USERID"), infoObj.getString("IDCARD"),
				DYNAMICFORM, FILEDATA);
		request.setAttribute("userAdrlist", list);
		request.getSession().setAttribute("ITEMNAME",
				infoObj.getString("ITEMNAME"));
		request.setAttribute("uInfo", uInfo);
		return "permatters/userinfo";
	}

	/**
	 * 
	 * @Description: 网上办事-保存事项申报基本信息
	 * @author zhang yachao
	 * @param itemInfo
	 *            实体类对象 封装参数用于生成xml字符串
	 * @param session
	 *            获取token
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/saveiteminfo")
	public String saveItemInfo(ItemInfo itemInfo, HttpServletRequest request)
			throws Exception {
		User user = (User) request.getSession().getAttribute("USER");
		if (user == null) {
			request.setAttribute("tips", "登录已失效");
			return "user/error";
		}
		String token = user.getAuthToken();
		if (StringUtils.isEmpty(token)) {
			request.setAttribute("tips", "登录已失效");
			return "user/error";
		}
		String itemId = itemInfo.getItemId();
		String DynamicForm = itemInfo.getDYNAMICFORM(); // 动态表单字段
		if ("1".equals(itemInfo.getIsExprecss())) {
			String addressData = getOrItemsService.modifyAddress(token,
					itemInfo.getUserid(),
					itemInfo.getCmbArea() + itemInfo.getAddress(), "",
					itemInfo.getPhone(), itemInfo.getIsDefault(),
					itemInfo.getName(), itemInfo.getTelNo(),
					itemInfo.getYzbm(), itemInfo.getCmbProvince(),
					itemInfo.getCmbCity());
			String addressID = JSONObject.parseObject(
					JSONObject.parseObject(addressData).getString("DATA"))
					.getString("ID");
			itemInfo.setExprecssId(addressID);
		} else {
			itemInfo.setExprecssId("");
		}

		String xml = XmlUtils.createXml(itemInfo); // 保存事项申报信息参数
		String data = getOrItemsService.saveItemInfo(token, xml);
		String code = JSONObject.parseObject(data).getString("code");
		if (!"0".equals(code)) {
			request.setAttribute("tips", "保存事项申报基本信息失败");
			return "user/error";
		}
		String Prokey = JSONObject.parseObject(
				JSONObject.parseObject(data).getString("DATA")).getString(
				"PROKEY");
		Receipt receipt = (Receipt) request.getSession()
				.getAttribute("receipt");
		receipt.setAPPLICANT(itemInfo.getEnterpriseName());
		receipt.setLINKMAN(itemInfo.getName());
		receipt.setPHONE(itemInfo.getPhone());
		request.getSession().setAttribute("itemInfo", itemInfo);
		request.getSession().setAttribute("PROKEYID", Prokey);
		request.getSession().setAttribute("receipt", receipt);
		return "redirect:itemdynamicform?itemId=" + itemId + "&prokeyid="
				+ Prokey + "&DynamicForm=" + DynamicForm;
	}

	/**
	 * 
	 * @Description:网上办事-动态加载事项表单
	 * @author zhang yachao
	 * @param itemId
	 *            事项id
	 * @param prokeyid
	 *            业务id
	 * @return
	 */
	@RequestMapping("/itemdynamicform")
	public String queryItemDynamicForm(String itemId, String prokeyid,
			String DynamicForm, HttpServletRequest request) {
		if (DynamicForm.equals("1")) {
			String data = getOrItemsService.queryItemDynamicForm(itemId,
					prokeyid);
			String str = JSONObject.parseObject(data).getString("DATA");
			List<DynamicReturn> list = JSON
					.parseArray(str, DynamicReturn.class);
			List<DynamicReturn> hiddenList = new ArrayList<>();
			List<DynamicReturn> commonList = new ArrayList<>();
			for (DynamicReturn dy : list) {
				String dySource = dy.getSource();
				if (dySource.length() > 2) {
					List<DynamicReturnSource> rSource = JSONObject.parseArray(
							dySource, DynamicReturnSource.class);
					dy.setSourceList(rSource);
				}
			}
			for (DynamicReturn dd : list) {
				if ("002003".equals(dd.getStyle_id())) {
					hiddenList.add(dd);
				} else {
					commonList.add(dd);
				}
			}
			/*
			 * for(DynamicReturn dd: list){
			 * if("002003".equals(dd.getStyle_id())){ hiddenList.add(dd); }else{
			 * commonList.add(dd); } }
			 */
			request.setAttribute("itemName",
					request.getSession().getAttribute("ITEMNAME"));
			request.getSession().setAttribute("list", list);
			request.setAttribute("hiddenList", hiddenList);
			request.setAttribute("commonList", commonList);
			request.setAttribute("itemId", itemId);
			request.setAttribute("prokeyid", prokeyid);
			return "permatters/itemDynamic";
		} else {
			return "redirect:getitemfilelist?itemId=" + itemId;
		}

	}

	/**
	 * 
	 * @Description: 网上办事-保存动态表单的信息
	 * @author zhang yachao
	 * @param dynamicInfo
	 * @return
	 */
	@RequestMapping("/saveitemdynamic")
	public String saveItemDynamicForm(String itemId, String prokeyid,
			String table_ename, HttpServletRequest request) {
		List<DynamicReturn> list = (List<DynamicReturn>) request.getSession()
				.getAttribute("list");
		JSONObject json = new JSONObject();
		json.put("itemid", itemId);
		json.put("prokeyid", prokeyid);
		json.put("table", table_ename);
		JSONArray array = new JSONArray();
		for (DynamicReturn d : list) {
			String field_ename = d.getField_ename();
			String filed_enameResult = request.getParameter(field_ename);
			JSONObject jsonObj = new JSONObject();
			jsonObj.put(field_ename, filed_enameResult);
			array.add(jsonObj);
		}
		json.put("field", array);
		String data = getOrItemsService
				.saveItemDynamicForm(json.toJSONString());
		request.getSession().removeAttribute("list");
		return "redirect:getitemfilelist?itemId=" + itemId;

	}

	/**
	 * 
	 * @Description: 网上办事-通过事项id获取该事项所需上传的材料
	 * @author zhang yachao
	 * @param itemId
	 * @return
	 */
	@RequestMapping("/getitemfilelist")
	public String getItemFileList(String itemId, String currentPage,
			HttpServletRequest request) {
		String data = getOrItemsService.getItemFileList(itemId);
		String code = JSONObject.parseObject(data).getString("code");
		if (!"0".equals(code)) {
			request.setAttribute("tips", "获取该事项所需上传的材料信息失败");
			return "user/error";
		}
		List<UploadFileInfo> upList = JSON.parseArray(JSON.parseObject(data)
				.getString("DATA"), UploadFileInfo.class);
		if (currentPage == null) {
			currentPage = "1";
		}
		// 当前页开始条数的索引
		int begin = 2 * (Integer.parseInt(currentPage) - 1);
		// 设置当前页结束条数的索引
		int end = 0;
		if (2 * Integer.parseInt(currentPage) > upList.size() - 1) {
			end = upList.size() - 1;
		} else {
			end = 2 * Integer.parseInt(currentPage) - 1;
		}
		List<UploadFileInfo> pageList = new ArrayList<>();
		for (int i = begin; i <= end; i++) {
			pageList.add(upList.get(i));
		}
		// 定义总页数
		int pageCount = (int) Math.ceil(upList.size() / 2.0);
		request.setAttribute("upList", pageList);
		request.setAttribute("itemId", itemId);
		request.setAttribute("currentPage", currentPage);
		request.setAttribute("pageCount", pageCount);
		return "permatters/new-file-upload";
	}

	/**
	 * 
	 * @Description: 设置上传材料类型参数,跳转到拍照页面
	 * @author zhang yachao
	 * @param fielName
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/takePhoto")
	public String takePhoto(String fielName, String itemId, String id,
			String currentPage, HttpServletRequest request) {
		int openType = 0;
		if (fielName.indexOf("身份证") != -1) {
			openType = 2;

		}
		Map<String, List<String>> imgMap = (Map<String, List<String>>) request
				.getSession().getAttribute("imgMap");
		if (imgMap != null) {
			List<String> list = imgMap.get(id);
			request.setAttribute("imgStrlist", list);
		}
		request.setAttribute("openType", openType);
		request.setAttribute("itemId", itemId);
		request.setAttribute("id", id);
		request.setAttribute("currentPage", currentPage);
		return "permatters/takePhotos";
	}

	/**
	 * 
	 * @Description: 调用高拍仪后将照片的base64信息传递到页面
	 * @author zhang yachao
	 * @param baseFile
	 * @param request
	 * @return
	 */
	@RequestMapping("/uploadfile")
	public String uploadFile(String baseFile, String itemId, String id,
			String currentPage, HttpServletRequest request) {
		List<Object> list = JSON.parseArray(baseFile);
		List<String> strList = new ArrayList<String>();
		for (Object li : list) {
			strList.add(li.toString());
		}
		String data = getOrItemsService.getItemFileList(itemId);
		List<UploadFileInfo> upList = JSON.parseArray(JSON.parseObject(data)
				.getString("DATA"), UploadFileInfo.class);
		List<UploadFileInfo> pageList = new ArrayList<>();

		int begin = 2 * (Integer.parseInt(currentPage) - 1);
		int end;
		if (2 * (Integer.parseInt(currentPage)) <= upList.size()) {
			end = 2 * (Integer.parseInt(currentPage));
		} else {
			end = upList.size();
		}

		// 跳转到文件上传页面显示首页，每页两条，在这里只拿前两条过去 显示首页
		for (int i = begin; i < end; i++) {
			pageList.add(upList.get(i));
		}

		// 上传图片需要CLID ，cLNAME, ImgMap中key为id
		// value为list<String>，nameAndIdMap里面key为id，value为CLNAME
		Map<String, String> nameAndIdMap = new HashMap<>();
		for (UploadFileInfo up : upList) {
			nameAndIdMap.put(up.getID(), up.getCLNAME());
		}

		request.setAttribute("upList", pageList);
		request.setAttribute("itemId", itemId);
		Map<String, List<String>> imgMap = null;
		if (request.getSession().getAttribute("imgMap") != null) {
			imgMap = (Map<String, List<String>>) request.getSession()
					.getAttribute("imgMap");
		} else {
			imgMap = new HashMap<String, List<String>>();
		}
		imgMap.put(id, strList);
		int pageCount = (int) Math.ceil(upList.size() / 2.0);
		request.setAttribute("pageCount", pageCount);
		request.setAttribute("currentPage", currentPage);
		request.getSession().setAttribute("nameAndIdMap", nameAndIdMap);
		request.getSession().setAttribute("imgMap", imgMap);
		return "permatters/new-file-upload";
	}

	/**
	 * 
	 * @Description: 事项材料上传
	 * @author zhang yachao
	 * @param itemid
	 * @param proKeyId
	 * @param clid
	 * @param clName
	 * @param fileBase64
	 * @param session
	 * @return
	 */
	@RequestMapping("/uploaditemfile")
	public String uploadItemFile(String itemid, HttpServletRequest request,
			RedirectAttributes attr) {
		User user = (User) request.getSession().getAttribute("USER");
		if (user == null) {
			request.setAttribute("tips", "登录已失效");
			return "user/error";
		}
		String token = user.getAuthToken();
		if (StringUtils.isEmpty(token)) {
			request.setAttribute("tips", "登录已失效");
			return "user/error";
		}
		Map<String, String> nameAndIdMap = (Map<String, String>) request
				.getSession().getAttribute("nameAndIdMap");
		Map<String, List<String>> imgMap = (Map<String, List<String>>) request
				.getSession().getAttribute("imgMap");
		String proKeyId = (String) request.getSession()
				.getAttribute("PROKEYID");
		request.getSession().removeAttribute("PROKEYID");
		String data = null;
		for (String key : imgMap.keySet()) {
			String clName = nameAndIdMap.get(key);
			List<String> imgList = imgMap.get(key);
			data = getOrItemsService.uploadItemFile(token, itemid, proKeyId,
					key, clName, imgList);
			if (StringUtils.isEmpty(data)
					|| !"0".equals(JSONObject.parseObject(data).getString(
							"code"))) {
				request.setAttribute("tips", clName + "材料上传失败");
				return "user/error";
			}
		}
		String sdata = JSONObject.parseObject(data).getString("DATA");
		String ItEMID = JSONObject.parseObject(sdata).getString("ITEMID");
		String PROKEYID = JSONObject.parseObject(sdata).getString("PROKEYID");
		String USERNAME = JSONObject.parseObject(sdata).getString("USERNAME");
		request.getSession().removeAttribute("imgMap");
		request.getSession().removeAttribute("nameAndIdMap");
		attr.addAttribute("itemId", ItEMID);
		attr.addAttribute("prokeyid", PROKEYID);
		return "redirect:submitItemAudit";
	}

	/**
	 * 事项申报提交审核
	 * 
	 * @param itemId
	 * @param prokeyid
	 * @param username
	 * @return
	 */
	@RequestMapping("/submitItemAudit")
	public String submitItemAudit(String itemId, String prokeyid,
			HttpServletRequest request) {
		String data = null;
		User user = (User) request.getSession().getAttribute("USER");
		if (user == null) {
			request.setAttribute("tips", "登录已失效");
			return "user/error";
		}
		String token = user.getAuthToken();
		if (StringUtils.isEmpty(token)) {
			request.setAttribute("tips", "登录已失效");
			return "user/error";
		}
		try {
			data = getOrItemsService.submitItemAudit(itemId, prokeyid, token);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (data == null
				|| !"0".equals(JSONObject.parseObject(data).getString("code"))) {
			request.setAttribute("tips", "事项申报提交审核失败");
			return "user/error";
		}

		String Trackid = JSONObject.parseObject(
				JSONObject.parseObject(data).getString("DATA")).getString(
				"TRACKID");
		JSONObject obj = new JSONObject();
		obj.put("type", "2");
		obj.put("data", Trackid);
		String base64 = null;
		try {
			base64 = Base64Util.toBase64(obj, 200, 200);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Receipt receipt = (Receipt) request.getSession()
				.getAttribute("receipt");
		SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String datetime = tempDate.format(new Date(System.currentTimeMillis()));
		receipt.setTRACKID(Trackid);
		receipt.setDATE(datetime);
		request.getSession().removeAttribute("receipt");
		request.setAttribute("Receipt", receipt);
		request.setAttribute("base64", base64);
		request.setAttribute("prokeyid", prokeyid);
		return "permatters/receipt";
	}

	/**
	 * 材料上传页面点击返回首页之后要清空存放图片的session
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/toindex")
	public String toindex(HttpServletRequest request) {
		request.getSession().removeAttribute("imgMap");
		request.getSession().removeAttribute("nameAndIdMap");
		try {
			userService.loginOut(request.getSession());
		} catch (Exception e) {
			request.setAttribute("tips", e.getMessage());
			return "user/error";
		}
		return "redirect:index.jsp";
	}

	/**
	 * 跳转到材料寄送页面
	 * 
	 * @return
	 */
	@RequestMapping("/toemail")
	public String toeamil(String prokeyid, HttpServletRequest request) {
		request.getSession().removeAttribute("prokeyid");
		request.setAttribute("prokeyid", prokeyid);
		return "permatters/emailfile";
	}

	/**
	 * 办理材料寄送
	 * 
	 * @param itemInfo
	 * @param request
	 * @return
	 */
	@RequestMapping("/material")
	public String materialOrderEms(ItemInfo itemInfo, HttpServletRequest request) {
		itemInfo.setTime(itemInfo.getTime() + ":00");
		String xml = null;
		try {
			xml = XmlUtils.createXml(itemInfo, "1");
		} catch (Exception e) {

			request.setAttribute("tips", "xml参数生成失败");
			return "user/error";
		}
		User user = (User) request.getSession().getAttribute("USER");
		if (user == null) {
			request.setAttribute("tips", "登录已失效");
			return "user/error";
		}
		String token = user.getAuthToken();
		if (StringUtils.isEmpty(token)) {
			request.setAttribute("tips", "登录已失效");
			return "user/error";
		}

		String data = getOrItemsService.materialOrderEms(token, xml);
		String code = JSONObject.parseObject(data).getString("code");
		if (!"0".equals(code)) {
			request.setAttribute("tips", "在线下单失败");
			return "user/error";
		}
		request.getSession().removeAttribute("itemInfo");
		request.getSession().removeAttribute("ITEMNAME");
		request.setAttribute("status", "在线下单成功");
		return "permatters/status";
	}

	/**
	 * 跳转动态表单拍照页面
	 */
	@RequestMapping("/dynamicfile")
	public String dynamicPhoto(String itemId, String prokeyid,
			HttpServletRequest request) {
		request.setAttribute("itemId", itemId);
		request.setAttribute("prokeyid", prokeyid);
		return "permatters/dynamicphoto";
	}

	/**
	 * 动态表单材料拍照上传
	 */
	@RequestMapping("/dynamicupload")
	public String dynamicUpload(String baseFile, String itemId,
			String prokeyid, HttpServletRequest request) {
		List<Object> list = JSON.parseArray(baseFile);
		List<String> strList = new ArrayList<String>();
		for (Object li : list) {
			strList.add(li.toString());
		}
		User user = (User) request.getSession().getAttribute("USER");
		if (user == null) {
			request.setAttribute("tips", "登录已失效");
			return "user/error";
		}
		String token = user.getAuthToken();
		String fileId = "100100";
		String data = getOrItemsService.uploadItemFile(token, itemId, prokeyid,
				fileId, "", strList);
		if (StringUtils.isEmpty(data)
				|| !"0".equals(JSONObject.parseObject(data).getString("code"))) {
			request.setAttribute("tips", "表单材料上传失败");
			return "user/error";
		}
		request.setAttribute("dyitemId", itemId);
		request.setAttribute("status", "上传表单材料成功");
		return "permatters/dynamicstatus";
	}
	/**
	 * 获取第一批上线事项
	 * @param request
	 * @param currentpage 当前第几页（无效）
	 * @param pagesize 当前页几行数据（无效）
	 */
	@RequestMapping("/getOneItemList")
	public String getOneItemList(HttpServletRequest request,
			String currentpage, String pagesize) {
		List<Items> firstItemList = new ArrayList<Items>();
		Page page = new Page();
		page.setCurrentpage(Integer.valueOf(currentpage));
		page.setPageSize(Integer.valueOf(pagesize));
		String data = getOrItemsService.getOneItemList("", currentpage,pagesize);
		JSONObject DATA = JSONObject.parseObject(data);
		if (data == null || !"0".equals(DATA.getString("code"))) {
			request.setAttribute("tips", "获取事项失败");
			return "user/error";
		}
		String jsonDate = DATA.getString("DATA");
		JSONArray jsonArray = JSONArray.parseArray(jsonDate);
		int currentRow = (int) Math.ceil(jsonArray.size()/ Double.valueOf(Integer.valueOf(pagesize)));
		page.setCurrentRow(currentRow);
		for (int i = 0; i < jsonArray.size(); i++) {
			JSONObject jsonObject = (JSONObject) jsonArray.get(i);
			if(jsonObject.getString("ITEMID")!=null && jsonObject.getString("ITEMID") !=""){
				Items items = new Items();
				items.setITEMID(jsonObject.getString("ITEMID"));
				items.setBSZNID(jsonObject.getString("BSZNID"));
				items.setNORMACCEPTDEPART(jsonObject.getString("NORMACCEPTDEPART"));
				items.setITEMNAME(jsonObject.getString("ITEMNAME"));
				items.setSXBM(jsonObject.getString("SXBM"));
				items.setNORMACCEPTDEPARTID(jsonObject.getString("NORMACCEPTDEPARTID"));
				items.setCODE(jsonObject.getString("CODE"));
				String SON_ITEM = jsonObject.getString("SON_ITEM");
				if (SON_ITEM.length()>2) {
					List<Items> sonItemList = JSONArray.parseArray(SON_ITEM,Items.class);
					items.setItemList(sonItemList);
				}else{
					List<Items> sonItemList1 = new ArrayList<Items>();
					items.setItemList(sonItemList1);
				}
				firstItemList.add(items);
			}
		}
		//事项排序
		for (int i = 0; i < firstItemList.size() - 1; i++) {
			// j开始等于0，
			for (int j = 0; j < firstItemList.size() - 1 - i; j++) {
				if (firstItemList.get(j).getItemList().size() < firstItemList.get(j + 1).getItemList().size()) {
					Items temp = firstItemList.get(j);
					firstItemList.set(j, firstItemList.get(j + 1));
					firstItemList.set(j + 1, temp);
				}
			}
		}
		
		request.setAttribute("firstItemList", firstItemList);
		request.setAttribute("page", page);
		return "permatters/first_item";
	}
	
	@RequestMapping("/getOneItemBszn")
	public String getFirstBszn(String itemId, HttpServletRequest request) {
		String data = getOrItemsService.getItem("", itemId);
		String code = JSONObject.parseObject(data).getString("code");
		if (!"0".equals(code)) {
			request.setAttribute("tips", "获取办事指南失败");
			return "user/error";
		}

		String fileData = JSONObject.parseObject(data).getString("FILE_DATA");
		String itemData = JSONObject.parseObject(data).getString("ITEM_DATA");
		List<FileData> fileDataList = JSON.parseArray(fileData, FileData.class);
		JSONObject itemDataJson = JSONObject.parseObject(itemData);
		ItemData itemDataObj = new ItemData(itemDataJson.getString("BLSJ"),
				itemDataJson.getString("BLWINDOW"),
				itemDataJson.getString("DEGREE"),
				itemDataJson.getString("ITEMID"),
				itemDataJson.getString("ITEMNAME"),
				itemDataJson.getString("JDTSDH"),
				itemDataJson.getString("NORMACCEPTDEPART"),
				itemDataJson.getString("NORMTIMELIMIT"),
				itemDataJson.getString("SCID"), itemDataJson.getString("SDYJ"),
				itemDataJson.getString("SFJE"), itemDataJson.getString("SFSF"),
				itemDataJson.getString("SXBM"),
				itemDataJson.getString("TRANSACT_CONDITION"),
				itemDataJson.getString("ZXMKZXDH"));
		itemDataObj.setISZXBL("true");
		Receipt receipt = new Receipt();
		// 为维护系统添加的type和types，后续可以删除
		request.setAttribute("types", request.getParameter("types"));
		request.setAttribute("type", request.getParameter("type"));
		receipt.setITMENAME(itemDataJson.getString("ITEMNAME"));
		receipt.setNORMACCEPTDEPART(itemDataJson.getString("NORMACCEPTDEPART"));
		receipt.setTELPHONE(itemDataJson.getString("ZXMKZXDH"));
		request.getSession().setAttribute("receipt", receipt);
		request.setAttribute("itemDataObj", itemDataObj);
		request.setAttribute("itemName", request.getParameter("itemName"));
		request.setAttribute("fileDataList", fileDataList);
		return "permatters/item"; // 跳转到网上办事-查询当前办理人、办理事项的基本信息
	}
	
}
